package com.tiankong.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiankong.product.entity.Attr;
import com.tiankong.product.entity.AttrAttrgroup;
import com.tiankong.product.mapper.AttrAttrgroupMapper;
import com.tiankong.product.service.AttrAttrgroupService;
import com.tiankong.product.service.AttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性&属性分组关联 服务实现类
 * </p>
 *
 * @author scl
 * @since 2021-03-22
 */
@Service
public class AttrAttrgroupServiceImpl extends ServiceImpl<AttrAttrgroupMapper, AttrAttrgroup> implements AttrAttrgroupService {

    @Autowired
    @Lazy
    private AttrService attrService;
    @Override
    public void saveRelation(AttrAttrgroup relation) {
        Integer count = query().eq("attr_id", relation.getAttrId()).eq("attr_group_id", relation.getAttrGroupId()).count();
        if (count<=0){
            save(relation);
        }
    }

    @Override
    public List<Attr> getRelationAttr(Long groupId) {
        Set<Long> attrIds = getRelationAttrIds(groupId);
        if (CollectionUtil.isNotEmpty(attrIds)){
            return attrService.listByIds(attrIds);
        }
        return null;
    }
    @Override
    public Set<Long> getRelationAttrIds(Long groupId) {
        return query().eq("attr_group_id", groupId).list().stream()
                    .map(AttrAttrgroup::getAttrId).collect(Collectors.toSet());
    }

    @Override
    public void removeRelationGroup(Set<Integer> groupIds) {
        update().in("attr_group_id",groupIds).remove();
    }

}
